//
//  SNNTableViewController.m
//  UI考试_团购应用
//
//  Created by lanou3g on 15-3-19.
//  Copyright (c) 2015年 胡航. All rights reserved.
//

#import "SNNTableViewController.h"
#import "SNNTableViewCell.h"
#import "NextTableViewController.h"
#import "Model.h"
#import "SignatrueEncryption.h"
#import "SNNViewController.h"
#import "DataHandle.h"

@interface SNNTableViewController ()<NextViewControlDelegate>

@property(nonatomic,strong)NSMutableArray *dataArray;

@property (nonatomic,strong)NSIndexPath *myIndex;

@end

@implementation SNNTableViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    //设置左键
    [self leftBarButton];
    //设置右按钮
    [self rightBarButton];
    //解析数据
    [self JXName];

}

//实现协议中的方法
-(void)backValue:(NSString *)textString
{
    self.name = textString;
    [self JXName];
}

//解析数据
-(void)JXName
{
    __unsafe_unretained typeof(self) weakSafe = self;
    
    if (self.name == nil) {
        
        self.name = @"生活家居";
    }
    //设置标题名字
    self.title = self.name;
    //加载视图
    [self loadView];
    //初始化数组
    self.dataArray = [NSMutableArray array];
    
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithObjectsAndKeys:@"上海",@"city",_name,@"category",@"30",@"limit",@"1",@"page",nil];
    //SHA1加密
       NSMutableDictionary *mDict = [SignatrueEncryption encryptedParamsWithBaseParams:dict];
    
    NSString *str = [NSString stringWithFormat:@"http://api.dianping.com/v1/deal/find_deals?appkey=42960815&sign=%@&city=%@&category=%@&limit=%@&page=%@",mDict[@"sign"],mDict[@"city"],mDict[@"category"],mDict[@"limit"],mDict[@"page"]];
    //把中文转换格式才能拼接到网址中
    NSString *encodedString = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    NSURL *url = [NSURL URLWithString:encodedString];
    //提出请求
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    //请求连接
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        
        //JSON解析
        NSDictionary *tempDict = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingAllowFragments) error:nil];
        
        for (NSDictionary *dict in tempDict[@"deals"]) {
            
            Model *m = [[Model alloc]init];
            [m setValuesForKeysWithDictionary:dict];
            [weakSafe.dataArray addObject:m];
            
        }
        //重新加载视图
        [weakSafe.tableView reloadData];
    }];
    
}

//设置右按钮
-(void)rightBarButton
{
    UIBarButtonItem *rightButton = [[UIBarButtonItem alloc]initWithTitle:@"刷新" style:(UIBarButtonItemStylePlain) target:self action:@selector(rightButtonAction:)];
    self.navigationItem.rightBarButtonItem = rightButton;

}
//右按钮响应事件
-(void)rightButtonAction:(UIBarButtonItem *)sender
{

}

//左按钮
-(void)leftBarButton
{
    UIBarButtonItem *leftButton = [[UIBarButtonItem alloc]initWithTitle:@"分类切换" style: UIBarButtonItemStyleDone target:self action:@selector(leftButtonAction:)];
    self.navigationItem.leftBarButtonItem = leftButton;

}
//左按钮响应事件
-(void)leftButtonAction:(UIBarButtonItem *)sender
{
    NextTableViewController *next = [[NextTableViewController alloc]init];
    //设置代理
    next.delegate = self;
    
    [self.navigationController pushViewController:next animated:YES];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

#pragma mark - Table view data source
//分区个数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}

//多少个cell
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return self.dataArray.count;

}

//返回cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    SNNTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (cell == nil) {
        cell = [[SNNTableViewCell alloc] initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:@"cell"];
    }
    

    Model *m = self.dataArray[indexPath.row];
    //给title赋值
    cell.title.text = m.title;
   
    //加载图片
    if (m.MyImage == nil && m.isLoading == NO) {
        //图片占位
        cell.myImage.image = [UIImage imageNamed:@"1.png"];
        //加载图片
        [m loadImage];
        //重新定义indexpath
        self.index = [NSIndexPath indexPathForItem:indexPath.row inSection:indexPath.section];
        
        //添加观察者
        [m addObserver:self forKeyPath:@"MyImage" options:(NSKeyValueObservingOptionNew) context:(__bridge void *)(indexPath)];
    }else
    {
        //添加视图
        cell.myImage.image = m.MyImage;
    }
     return cell;
}

//图片发生变化调用这个方法
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    
    UIImage *tempImage = change[NSKeyValueChangeNewKey];
    
    if ([tempImage isEqual:[NSNull null]]) {
        return;
    }
    
    NSIndexPath *indexPath = (__bridge NSIndexPath *)(context);

    NSArray *indexArray = [self.tableView indexPathsForVisibleRows];
    
    for (NSIndexPath *paths in indexArray) {
        if ([self.index isEqual:paths]) {
            
            SNNTableViewCell *cell = (SNNTableViewCell *)[self.tableView cellForRowAtIndexPath:indexPath];
            cell.myImage.image = tempImage;
            
            [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:(UITableViewRowAnimationAutomatic)];
        }
    }
    //移除观察者
    [object removeObserver:self forKeyPath:@"MyImage"];

}

//用segue传值的话不走这个方法
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
   
    //此方法是不可行的,因为只能使用push才能把值push过去
   //SNNViewController *s = [[SNNViewController alloc]init];
//    
//    s.Model = self.dataArray[indexPath.row];
//    
//    s.indexPath = indexPath;
//    NSLog(@"%ld",(long)s.indexPath.row);
//    NSLog(@"%ld",(long)s.indexPath.section);
//    [DataHandle shareHandle].dataArr = self.dataArray;
//    
   // _myIndex = indexPath;
   // NSLog(@"%@",indexPath);

}

//segue传值
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    //sender就是我们点的那个cell
   self.myIndex = [self.tableView indexPathForCell:sender];
    
    //判断是哪一个segue
    if ([segue.identifier isEqualToString:@"push"]) {
        
        //拿到目的控制器
        SNNViewController *temp = segue.destinationViewController;
        //加载目的控制器
        [temp loadView];
        //给model类赋值
        Model *m = self.dataArray[_myIndex.row];
        NSLog(@"%@",_myIndex);
        //传值
        temp.HHtitle.text = m.title;
        temp.HHLabel.text = m.content;
        temp.HHImage.image = m.MyImage;
    }
}

@end
